<template>
    <div>
        <div>
            <h3>用户详情 <button class="back-button" @click="goBack">返回</button></h3>
        </div>
        <div v-if="loading" class="loading">加载中...</div>

        <div v-else-if="error" class="error-message">
            <p>{{ error }}</p>
            <button class="retry-button" @click="fetchUserInfo">重试</button>
        </div>

        <div v-else class="acct-info">
            <!-- 上区域 - 高度300px，分为左中右三个区域 -->
            <div class="top-section">
                <div class="left-area">
                    <div class="user-info">
                        <table class="user-info-table">
                            <tbody>
                                <tr>
                                    <td>用户ID</td>
                                    <td>{{ userInfo.userId }}</td>
                                    <td>基金代码</td>
                                    <td>{{ userInfo.fundCode }}</td>
                                </tr>
                                <tr>
                                    <td>模拟时间</td>
                                    <td colspan="3">{{ userInfo.simTime }}</td>
                                </tr>
                                <tr>
                                    <td>第{{ userInfo.days }}天</td>
                                    <td>第{{ userInfo.weeks }}周</td>
                                    <td>HOT</td>
                                    <td>{{ userInfo.hotAll }}</td>
                                </tr>
                                <tr>
                                    <td>当前价格</td>
                                    <td>{{ userInfo.curPrice }}</td>
                                    <td>HOT500</td>
                                    <td>{{ userInfo.hot500 }}</td>
                                </tr>
                                <tr>
                                    <td>价格系数</td>
                                    <td>{{ userInfo.curPriceLog }}</td>
                                    <td>HOT300</td>
                                    <td>{{ userInfo.hot300 }}</td>
                                </tr>
                                <tr>
                                    <td>系数变化</td>
                                    <td>{{ userInfo.priceLogChange }}</td>
                                    <td>a</td>
                                    <td>b</td>
                                </tr>
                            </tbody>
                        </table>

                    </div>
                </div>
                <div class="middle-area">
                    <h3>账户交易记录</h3>
                    <div class="table-container">
                        <table class="accounts-table">
                            <thead>
                                <tr>
                                    <th>日期</th>
                                    <th>账户价值</th>
                                    <th>基金价值</th>
                                    <th>底仓价值</th>
                                    <th>现金</th>
                                    <th>转入</th>
                                    <th>利润</th>
                                    <th>交易额</th>
                                    <th>pLog</th>
                                    <th>flatRot</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="(account, index) in userInfo.accounts" :key="index">
                                    <td>{{ account.dealDate }}</td>
                                    <td>{{ account.acctValueTot }}</td>
                                    <td>{{ account.fundValueTot }}</td>
                                    <td>{{ account.baseFundValue }}</td>
                                    <td>{{ account.cashBalance }}</td>
                                    <td>{{ account.transIn }}</td>
                                    <td>{{ account.profit }}</td>
                                    <td>{{ account.dealAmount }}</td>
                                    <td>{{ account.priceLog }}</td>
                                    <td>{{ account.flatRot }}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="right-area">
                    <div class="table-container">
                        <table class="accounts-table">
                            <tbody>
                                <tr>
                                    <td>系数卖出额</td>
                                    <td>
                                        <div v-if="userInfo.advice.priceLogSellAmount">{{
                                            userInfo.advice.priceLogSellAmount }}</div>
                                        <div v-else>0</div>
                                    </td>
                                    <td>价值卖出额</td>
                                    <td>
                                        <div v-if="userInfo.advice.valueSellAmount">{{ userInfo.advice.valueSellAmount
                                        }}</div>
                                        <div v-else>0</div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <div>
                        <button class="query-button" @click="submitDeal">提交</button>
                    </div>
                    <div v-if="userInfo.advice.existFixBuy">
                        <div>
                            <input type="checkbox" value="fixBuy" v-model="deal.fixBuy" />
                            <label for="fixBuy"> 定投{{ userInfo.advice.fixBuyDeal.dealAmount }}</label>
                        </div>
                    </div>
                    <div v-if="userInfo.advice.existPriceLogBuy" class="checkbox-list-flex-row">
                        系数买入：
                        <div v-for="buy in userInfo.advice.priceLogBuys">
                            <input type="checkbox" :id="buy.relaSubDealId" :value="buy.dealAmount"
                                v-model="deal.priceLogBuys" />
                            <label :for="buy.relaSubDealId"> {{ buy.dealAmount }}</label>
                        </div>
                    </div>
                    <div v-if="userInfo.advice.existValueBuy" class="checkbox-list-flex-row">
                        价值买入：
                        <div v-for="buy in userInfo.advice.valueBuys">
                            <input type="checkbox" :id="buy.relaSubDealId" :value="buy.dealAmount"
                                v-model="deal.valueBuys" />
                            <label :for="buy.relaSubDealId"> {{ buy.dealAmount }}</label>
                        </div>
                    </div>
                    <div v-if="userInfo.advice.existShortBuy" class="checkbox-list-flex-row">
                        超跌买入：
                        <div v-for="buy in userInfo.advice.shortBuys">
                            <input type="checkbox" :id="buy.relaSubDealId" :value="buy.relaSubDealId"
                                v-model="deal.shortBuys" />
                            <label :for="buy.relaSubDealId"> {{ buy.dealAmount }}</label>
                        </div>
                    </div>

                    <div v-if="userInfo.advice.existProfitSell" class="checkbox-list-flex-row">
                        获利卖出：
                        <div v-for="sell in userInfo.advice.profitSells">
                            <input type="checkbox" :id="sell.relaSubDealId" :value="sell.relaSubDealId"
                                v-model="deal.profitSells">{{ sell.dealAmount }}</input>
                        </div>
                    </div>
                    <p>您已选择：ps:{{ deal.profitSells }}; sb:{{ deal.shortBuys }}</p>


                </div>
            </div>

            <!-- 中区域 - 高度500px，分为左右两个区域 -->
            <div class="middle-section">
                <div class="left-half">
                    <div class="dealstat-chart-container">
                        <EChartsWrapper :option="dealStatOption" />
                    </div>
                </div>
                <div class="right-half">

                    <div class="dealstat-chart-container">
                        <EChartsWrapper :option="dealStat6Option" />
                    </div>
                </div>
            </div>
            <!-- 中下区域 - 高度500px，分为左右两个区域 -->
            <div class="middle-section">
                <div class="left-half">
                    <div class="dealstat-chart-container">
                        <EChartsWrapper :option="dealStat3Option" />
                    </div>
                </div>
                <div class="right-half">
                    <div class="dealstat-chart-container">
                        <EChartsWrapper :option="dealStat12Option" />
                    </div>

                </div>
            </div>

            <!-- 下区域 - 高度200px，分为四个区域 -->
            <div class="bottom-section">
                <div class="quarter-area">
                    <div class="hot-chart-container">
                        <EChartsWrapper :option="hotOption" />
                    </div>
                </div>
                <div class="quarter-area">区域2</div>
            </div>
        </div>
    </div>


</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { userApi } from '../api'
import EChartsWrapper from '../components/EChartsWrapper.vue'
import * as echarts from 'echarts'

const router = useRouter()
const route = useRoute()
const userId = ref(route.params.userId)
const userInfo = ref({})
const errorMessage = ref('')
const deal = ref({
    fixBuy: false,
    shortBuys: [],
    profitSells: [],
    valueSellAmount: [],
    priceLogSellAmount: [],
    valueBuys: [],
    priceLogBuys: []
})

const dealStatOption = ref({})
const dealStat3Option = ref({})
const dealStat6Option = ref({})
const dealStat12Option = ref({})
const hotOption = ref({})

const loading = ref(true)
const error = ref('')

const goBack = () => {
    router.push('/')
}

const fetchUserInfo = async () => {
    loading.value = true
    error.value = ''

    try {
        // 调用API获取用户投资建议信息
        const response = await userApi.getUserAdvice(userId.value)
        if (response) {
            // 处理返回的数据
            handleResponse(response.data)
            initDeal()
        } else {
            error.value = '获取用户信息失败'
        }
    } catch (err) {
        console.error('获取用户信息失败:', err)
        error.value = '获取用户信息失败，请稍后再试'
    } finally {
        loading.value = false
    }
}

const submitDeal = async () => {
    loading.value = true
    error.value = ''

    try {
        const response = await userApi.submitDeal(userId.value, deal.value)
        if (response) {
            handleResponse(response.data)
            initDeal()
            errorMessage.value = '提交成功'
        } else {
            errorMessage.value = '提交失败'
        }
    } catch (error) {
        console.error('提交交易失败:', error)
        errorMessage.value = '提交失败，请稍后再试'
    } finally {
        loading.value = false
    }
}

onMounted(() => {
    fetchUserInfo()
})

function initDeal() {
    deal.value = {
        fixBuy: false,
        shortBuys: [],
        profitSells: [],
        valueSellAmount: [],
        priceLogSellAmount: [],
        valueBuys: [],
        priceLogBuys: []
    }
}
function handleResponse(response) {
    userInfo.value = {
        name: response.userName || '未知用户',
        userId: response.userId,
        fundCode: response.fundCode,
        fundName: response.fundName,
        curPrice: response.curPrice,
        curPriceLog: response.curPriceLog,
        latestPrice: response.latestPrice,
        priceDate: response.priceDate,
        simDate: response.simDate,
        simTime: response.simTime,
        startDate: response.startDate,
        days: response.days,
        weeks: response.weeks,
        hotAll: response.hot,
        hot500: response.hot500,
        hot300: response.hot300,
        priceLog: response.priceLog,
        priceLogChange: response.priceLogChange,

        // 账户信息
        accounts: response.accounts || [],
        // 投资建议
        advice: response.advice || {},
        // 交易统计
        subDealChart1: response.subDealChart1 || {},
        subDealChart3: response.subDealChart3 || {},
        subDealChart6: response.subDealChart6 || {},
        subDealChart12: response.subDealChart12 || {},
        // 热度分析
        hotChart: response.hotChart || {}
    }
    setSubDealStatOption()
    setHotOption()

}

function setHotOption() {
    if (userInfo) {
        hotOption.value = {
            title: { text: userInfo.value.hotChart.title },
            tooltip: { trigger: 'axis' },
            xAxis: {
                type: userInfo.value.hotChart.xAxisType,
                data: userInfo.value.hotChart.xAxis,
                axisTick: {
                    alignWithLabel: true
                }
            },
            yAxis: userInfo.value.hotChart.yAxis,
            series: userInfo.value.hotChart.series,
            dataZoom: [
                {
                    type: 'inside',
                    start: 50,
                    end: 100
                },
                {
                    show: true,
                    type: 'slider',
                    top: '90%',
                    start: 50,
                    end: 100
                }
            ],
            legend: {
                data: ['HAll', 'H500', 'H300', 'pLog'],
                top: 20
            },
            animation: false
        }
    }
}

function setSubDealStatOption() {
    if (userInfo) {
        dealStatOption.value = {
            title: { text: userInfo.value.subDealChart1.title },
            tooltip: { trigger: 'axis' },
            xAxis: {
                type: userInfo.value.subDealChart1.xAxisType,
                data: userInfo.value.subDealChart1.xAxis,
                axisTick: {
                    alignWithLabel: true
                }
            },
            yAxis: userInfo.value.subDealChart1.yAxis,
            series: userInfo.value.subDealChart1.series,
            animation: false,
            legend: {
                data: userInfo.value.subDealChart1.legend.data,
                top: 20
            },
        }

        dealStat3Option.value = {
            title: { text: userInfo.value.subDealChart3.title },
            tooltip: { trigger: 'axis' },
            xAxis: {
                type: userInfo.value.subDealChart3.xAxisType,
                data: userInfo.value.subDealChart3.xAxis,
                axisTick: {
                    alignWithLabel: true
                }
            },
            yAxis: userInfo.value.subDealChart3.yAxis,
            series: userInfo.value.subDealChart3.series,
            animation: false,
            legend: {
                data: userInfo.value.subDealChart3.legend.data,
                top: 20
            },
        }

        dealStat6Option.value = {
            title: { text: userInfo.value.subDealChart6.title },
            tooltip: { trigger: 'axis' },
            xAxis: {
                type: userInfo.value.subDealChart6.xAxisType,
                data: userInfo.value.subDealChart6.xAxis,
                axisTick: {
                    alignWithLabel: true
                }
            },
            yAxis: userInfo.value.subDealChart6.yAxis,
            series: userInfo.value.subDealChart6.series,
            animation: false,
            legend: {
                data: userInfo.value.subDealChart6.legend.data,
                top: 20
            },
        }

        dealStat12Option.value = {
            title: { text: userInfo.value.subDealChart12.title },
            tooltip: { trigger: 'axis' },
            xAxis: {
                type: userInfo.value.subDealChart12.xAxisType,
                data: userInfo.value.subDealChart12.xAxis,
                axisTick: {
                    alignWithLabel: true
                }
            },
            yAxis: userInfo.value.subDealChart12.yAxis,
            series: userInfo.value.subDealChart12.series,
            animation: false,
            legend: {
                data: userInfo.value.subDealChart12.legend.data,
                top: 20
            },
        }
        // console.log('dealStatOption:', dealStatOption)
    }
}
</script>


<style scoped>
.acct-detail-container {
    width: 100%;
    max-width: 100%;
    margin: 0;
    padding: 0;
}

.back-button {
    background-color: #f0f0f0;
    border: none;
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
    margin-bottom: 10px;
}

.back-button:hover {
    background-color: #e0e0e0;
}

h1 {
    color: #333;
    margin-bottom: 20px;
}

h3 {
    color: #333;
    margin-bottom: 10px;
}

.table-container {
    max-height: 250px;
    overflow-y: auto;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.accounts-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 14px;
    border: 1px solid #ddd;
}

.accounts-table th {
    background-color: #f5f5f5;
    padding: 2px;
    text-align: left;
    font-weight: bold;
    position: sticky;
    top: 0;
    z-index: 1;
    border: 1px solid #ddd;
}

.accounts-table td {
    padding: 2px;
    border: 1px solid #ddd;
}

.accounts-table tr:hover {
    background-color: #f9f9f9;
}

.loading {
    text-align: center;
    padding: 40px;
    font-size: 18px;
    color: #666;
}

.error-message {
    text-align: center;
    padding: 20px;
    color: #d9534f;
    background-color: #f9f2f2;
    border-radius: 4px;
    margin-bottom: 2px;
}

.retry-button {
    background-color: #d9534f;
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
    margin-top: 1px;
}

.acct-info {
    display: flex;
    flex-direction: column;
    gap: 2px;
    width: 100%;
    height: 100%;
}

/* 上区域样式 */
.top-section {
    display: flex;
    height: 300px;
    margin-bottom: 2px;
    border: 1px solid #ddd;
    border-radius: 0;
    width: 100%;
}

.left-area {
    width: 20%;
    background-color: #f5f5f5;
    padding: 1px;
    border-right: 1px solid #ddd;
}

.middle-area,
.right-area {
    width: 40%;
    padding: 1px;
}

.middle-area {
    border-right: 1px solid #ddd;
    background-color: #fafafa;
}

/* 中区域样式 */
.middle-section {
    display: flex;
    height: 400px;
    margin-bottom: 2px;
    border: 1px solid #ddd;
    border-radius: 0;
    width: 100%;
}

.left-half,
.right-half {
    flex: 1;
    padding: 1px;
}

.left-half {
    border-right: 1px solid #ddd;
    background-color: #f9f9f9;
}

/* 下区域样式 */
.bottom-section {
    display: flex;
    height: 400px;
    border: 1px solid #ddd;
    border-radius: 0;
    width: 100%;
}

.quarter-area {
    flex: 1;
    padding: 1px;
    border-right: 1px solid #ddd;
    background-color: #f8f8f8;
}

.quarter-area:last-child {
    border-right: none;
}

.query-button {
    background-color: #4CAF50;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
    transition: background-color 0.3s;
}

.user-info-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 14px;
    border: 1px solid #ddd;

}

.user-info-table td {
    padding: 2px;
    border: 1px solid #ddd;
}

.checkbox-list-flex-column {
    display: flex;
    flex-wrap: wrap;
    flex-direction: column;
    /* 或者使用 row 来实现横排 */
}

.checkbox-list-flex-row {
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
    /* 或者使用 row 来实现横排 */
}

.dealstat-chart-container {
    width: 100%;
    height: 50vh;
    padding: 2px;
    box-sizing: border-box;
}
</style>